//
//  PhotosTableViewCell.m
//  Jyxt
//
//  Created by 刘日 on 17/5/17.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "PhotosTableViewCell.h"
#import "LemonBestView.h"
#import <YYKit.h>


#define PADDING 16
#define SPACE 17
#define LINE_COUNT 3

static NSMutableArray<UIImage *> *_photos;

@implementation PhotosTableViewCell 

+ (NSMutableArray<UIImage *> *)photos{
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    self.photoContentView.onTap = ^(UIView *view){
        if ([PhotosTableViewCell photos].count <= 0) {
            // 添加照片
            [self addPhoto];
        }
    };
    [self refreshPhotos];
}

- (void)layoutSubviews{
    [self refreshPhotos];
}

+ (CGFloat)calculateHeight{
    CGFloat width = (LK_SIZE_SCREEN_WIDTH - PADDING * 2 - (LINE_COUNT - 1) * SPACE) / LINE_COUNT;
    CGFloat height = width / 4 * 3;
    NSInteger count = MIN(5, [PhotosTableViewCell photos].count);
    CGFloat result = (count <= 0 ? 135 : (PADDING * 2 + (height + SPACE) * ceil((count + 1) * 1.0 / LINE_COUNT) - SPACE));
    return result;
}

- (void)refreshPhotos{
    [self.photoContentView removeAllChildViews];
    if ([PhotosTableViewCell photos].count > 0) {
        // 有已经添加的照片
        for (NSInteger i = 0 ; i <= [PhotosTableViewCell photos].count; i ++) {
            CGFloat width = (LK_SIZE_SCREEN_WIDTH - PADDING * 2 - (LINE_COUNT - 1) * SPACE) / LINE_COUNT;
            CGFloat height = width / 4 * 3;
            CGFloat x = PADDING + (width + SPACE) * (i % LINE_COUNT);
            CGFloat y = floor(i * 1.0 / LINE_COUNT) * (height + SPACE) + PADDING;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
            if (i < [PhotosTableViewCell photos].count) {
                imageView.image = [PhotosTableViewCell photos][i];
                imageView.tag = i;
                UIImageView *delIcon = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"ig_common_delete"]];
                delIcon.frame = CGRectMake(imageView.frame.size.width - 24, 4, 20, 20);
                [imageView addSubview: delIcon];
                imageView.onTap = ^(UIView *view){
                    UIAlertController *alert = [UIAlertController  alertControllerWithTitle: @"删除照片" message: @"您确定要删除这张照片吗？" preferredStyle: UIAlertControllerStyleAlert];
                    [alert addAction: [UIAlertAction actionWithTitle: @"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[PhotosTableViewCell photos] removeObjectAtIndex: view.tag];
                        [self.tableView reloadRow: 0 inSection: 0 withRowAnimation: UITableViewRowAnimationAutomatic];
//                        [self refreshPhotos];
                    }]];
                    [alert addAction: [UIAlertAction actionWithTitle: @"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                    }]];
                    [[LKFreeCtrl getTopViewController] presentViewController: alert animated: YES completion: nil];
                };
            }
            else{
                if ([PhotosTableViewCell photos].count >= 6)
                    return;
                imageView.image = LKImageNamed(@"ig_common_camera");
                imageView.backgroundColor = [ExtenColor colors].c_f5f5f5;
                imageView.contentMode = UIViewContentModeCenter;
                imageView.onTap = ^(UIView *view){
                    [self addPhoto];
                };
            }
            [self.photoContentView addSubview: imageView];
        }
    }
    self.cameraIcon.hidden = [PhotosTableViewCell photos].count > 0;
    self.titleLabel.hidden = [PhotosTableViewCell photos].count > 0;
    
}

- (void)addPhoto{
    LemonBestView *as = [LemonBestView defaultActionSheetView];
    [as clear];
    as.headViewHeight = 44;
    as.title =  @"请您选择照片来源";
    LemonBestItem *cancel = [[LemonBestItem alloc] initWithTitle: @"取消" onTouchBlock:^(LemonBestItem *item) {
        [as hide];
    }];
    ((UILabel *)cancel.contentView).textColor = [UIColor redColor];
    [as addAction: cancel groupIndex: 0];
    [as addActionGroup];
    as.backViewControllerScale = 0.9;// 设置1 就没有后边viewController的缩放效果了
    [as addAction: [[LemonBestItem alloc] initWithTitle: @"从手机相册选择" onTouchBlock:^(LemonBestItem *item) {
        [self selectFromAlbum];
        [as hide];
    }] groupIndex:1];
    [as addAction: [[LemonBestItem alloc] initWithTitle: @"拍照" onTouchBlock:^(LemonBestItem *item) {
        [self takePhoto];
        [as hide];
    }] groupIndex:1];
    [as show];
}

#pragma mark - 从手机相册选择的点击方法
- (void)selectFromAlbum {
    NSLog(@"从手机相册选择");
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [LKFreeCtrl presentViewController: imagePicker];
    });
}

#pragma mark - 拍照按钮的点击方法
- (void)takePhoto {
    BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if (!isCamera) { //若不可用，弹出警告框
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"对不起，无法使用摄像头" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.delegate = self;    //设置代理，遵循UINavigationControllerDelegate,UIImagePickerControllerDelegate协议
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [LKFreeCtrl presentViewController: imagePicker];
    });
}

#pragma mark - 相册选择完照片添加到 imageview 上
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    TOCropViewController *cropController = [[TOCropViewController alloc] initWithCroppingStyle: TOCropViewCroppingStyleDefault image: [info objectForKey:UIImagePickerControllerOriginalImage]];
    cropController.aspectRatioLockEnabled = NO;
    cropController.aspectRatioPickerButtonHidden = YES;
    cropController.customAspectRatio = CGSizeMake(4, 3);
    cropController.delegate = self;
    [picker pushViewController:cropController animated:YES];
}

- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle{
    [[PhotosTableViewCell photos] addObject: [self scaleImage:image toKb: 1024]];
    if (_tableView) {
        [_tableView reloadRow: 0  inSection:0  withRowAnimation: UITableViewRowAnimationBottom];
    }
    [cropViewController dismissViewControllerAnimated: YES completion: nil];
}

- (void)cropViewController:(TOCropViewController *)cropViewController didFinishCancelled:(BOOL)cancelled{
    [cropViewController dismissViewControllerAnimated: YES completion:^{
        
    }];
}

//图片压缩到指定大小
- (UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    if (!image) {
        return image;
    }
    if (kb<1) {
        return image;
    }
    kb*=1024;
    NSLog(@"当前大小:%fkb",(float)[UIImageJPEGRepresentation(image, 1) length]/1024.0f);
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"当前大小:%fkb",(float)[imageData length]/1024.0f);
    UIImage *compressedImage = [[UIImage alloc] initWithData:imageData];
    return [self imageByScalingAndCroppingForSize:CGSizeMake(800, 800) Image:compressedImage];
}

- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize Image:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.25;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.25;
        }
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

@end
